use anyhow::Result;
use template::router::get_router;
use template::AppConfig;
use tracing::info;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::Layer;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

#[tokio::main]
async fn main() -> Result<()> {
    let config = AppConfig::load()?;
    let console = Layer::new()
        .with_ansi(true)
        .with_line_number(true)
        .with_target(true)
        .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
        .with_thread_ids(true) // include the thread ID of the current thread
        .with_thread_names(true) // include the name of the current thread
        .json();
    tracing_subscriber::registry()
        .with(LevelFilter::INFO)
        .with(console)
        .init();

    let address = format!("0.0.0.0:{}", config.server.port);
    let app = get_router(config).await?;
    let listener = tokio::net::TcpListener::bind(address.clone()).await?;
    info!("starting server on {}", address);
    axum::serve(listener, app.into_make_service()).await?;
    Ok(())
}
